package communication.common.business.util;

import communication.common.business.base.IpType;
import communication.common.business.base.OsTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 *  系统参数工具
 * @author mac
 */
@Slf4j
public class OsParamUtil {


    private static final String[] ethList={"wlan0","en0","eth0"};

    /**
     * 获取当前操作系统的类型
     *  0 — max os ;
     *  1 - linux ;
     *  2 - windows ;
     * @return  OsTypeEnum
     */
    public static OsTypeEnum getOsType() throws Exception {
        return OsTypeEnum.getByName(System.getProperty("os.name"));
    }


    /**
     * 获取本地网卡的ip地址
     * @param eth  要读取的网卡 , 如果为空，按照 无线->有线网卡 的优先级读取
     * @param ipType 要读取的ip类型,ipv4 或者ipv6. 如果为空，默认读取ipv4
     *
     *
     * @return ip地址
     */
    public static String getLocalIpAddress(String eth , String ipType) throws Exception {
        OsTypeEnum osType = getOsType();
        log.info("this system type : {}",osType);
        IpType type=IpType.IP_V4;
        if(!StringUtils.isEmpty(ipType)){
            type=IpType.valueOf(ipType);
        }

        switch (osType){
            case MAC_OS:
            case LINUX:
                return getLocalIpFromMacOs(eth,type);
            default:
                throw new Exception("not support os system!");
        }
    }

    /**
     * 获取macos系统的ip地址
     * @return String ip地址
     */
    public static String getLocalIpFromMacOs(String eth, IpType ipType) throws IOException {
        String host=null;
        // 先读取en0网卡，
        if(StringUtils.isEmpty(eth)){
            for (String ethStr :ethList) {
                host=getSpecialIpAddressFromOsx(ethStr, ipType);
                if(!StringUtils.isEmpty(host)){
                    return host;
                }
            }
        }
        host = getSpecialIpAddressFromOsx(eth, ipType);
        return host;
    }


    private static String getSpecialIpAddressFromOsx(String eth,IpType ipType) throws IOException {
        boolean inet6Flg=false;
        if(ipType.equals(IpType.IP_V6)){
            inet6Flg=true;
        }
        Process process = Runtime.getRuntime().exec("ifconfig "+eth);
        BufferedReader reader = new BufferedReader(new InputStreamReader( process.getInputStream()));
        String line=null;
        while( (line=reader.readLine())!=null){
            // trim是用来去除 每行开头的 \t
            String trim = line.trim();
            // 由于ipv6与ipv4都是 inet开头（inet , inet6） ,所以需要对inet做特殊判断
            if(inet6Flg){
                if(trim.startsWith(ipType.getName())){
                    line = trim.split(" ")[1].trim();
                    break;
                }
            }else {
                if( !inet6Flg  && trim.startsWith(ipType.getName()) && !trim.startsWith("inet6")){
                    line = trim.split(" ")[1].trim();
                    break;
                }
            }

        }
        return line;
    }


    /**
     * 获取 mac os系统的mac地址
     * @param name 要读取的网卡,如果为null，则按照 无线网卡->有线网卡 的优先级读取mac地址
     * @return 网卡地址
     */
    private static String getLocalMacFromOsx(String name) throws Exception {
        String macAddress=null;
        if(!StringUtils.isEmpty(name)){
            macAddress=getSpecialMacAddressFromOsx(name);
        }

        // 优先读取en0网卡，en0网卡不存在，再读取eth0网卡
        if(macAddress==null){
            macAddress=getSpecialMacAddressFromOsx("en0");
        }

        if(macAddress==null){
            macAddress=getSpecialMacAddressFromOsx("eth0");
        }

        if(macAddress==null){
            throw new Exception("get  mac address of mac-os-x fail!");
        }
        return macAddress;
    }


    /**
     *  todo:
     * 获取 linux系统的mac地址
     * @return 网卡地址
     */
    private static String getLocalMacFromUnix() throws Exception {
        return null;
    }



    /**
     * 获取指定网卡的地址
     * @param eth  要查询的网卡名称，例如：eth0,en0
     * @return 网卡地址
     */
    private static String getSpecialMacAddressFromOsx(String eth) throws IOException {
        Process process = Runtime.getRuntime().exec("ifconfig "+eth);
        BufferedReader reader = new BufferedReader(new InputStreamReader( process.getInputStream()));
        String line=null;
        while( (line=reader.readLine())!=null){
            // trim是用来去除 每行开头的 \t
            if(line.trim().startsWith("ether")){
                line = line.split("ether")[1].trim();
                break;
            }
        }
        return line;
    }



    /**
     * 获取网卡信息
     *  默认获取eth0网卡的mac地址，如果eth0不存在，则获取en0的；
     * @return 网卡地址
     */
    public static String getLocalMac(String name){
        String macAddress=null;
        // 根据操作系统类型获取mac地址
        try{
            OsTypeEnum osType = getOsType();
            switch (osType){
                case MAC_OS:
                    macAddress = getLocalMacFromOsx(name);
                    break;
                default:
                    break;
            }
        }catch (Exception e){
            e.printStackTrace();
            macAddress=e.getMessage();
        }

//        log.info(" 当前网卡地址:{}",OsParamUtil.getLocalMac());
        return macAddress;
    }


}
